package com.qf.springbootdemo03.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author q
 * @version V1.0
 * @date 2021/11/25
 **/
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello~";
    }

    @RequestMapping("/showname")
    public String showName(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null == principal){
            return "匿名";
        }
        if (principal instanceof UserDetails){
            //经过认证的
            User user = (User) principal;
            //System.out.println(user.getUsername());
            //System.out.println(user.getPassword());
            //System.out.println(user.getAuthorities());
            return user.getUsername();
        }
        //当前资源是否经过Security，如果 经过 +未登录 +直接放行了，那么会给一个临时用户anonymousUser，需要处理
        if ("anonymousUser".equals(principal)){
            return "临时用户：anonymousUser";
        }
        return principal.toString();
    }

    @RequestMapping("/success")
    public String success(){
        return "SUCCESS";
    }
}
